package com.haoxuer.discover.filter.impl;


import com.haoxuer.discover.filter.api.FilterTemplate;
import com.haoxuer.discover.filter.api.FilterChainTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class FilterChainImpl<Request,Response>  implements FilterChainTemplate<Request,Response> {


  private final List<FilterTemplate> filters;

  private Iterator<FilterTemplate> iterator;

  public void addFilter(FilterTemplate filter) {
    this.filters.add(filter);
  }


  public FilterChainImpl(FilterTemplate... filters) {
    this.filters = new ArrayList<>();
    if (filters != null) {
      for (FilterTemplate filter : filters) {
        this.filters.add(filter);
      }
    }
  }

  private static List<FilterTemplate> initFilterList(FilterTemplate... filters) {
    return Arrays.asList(filters);
  }

  @Override
  public void doFilter(Request request, Response response) {
    if (this.iterator == null) {
      this.iterator = this.filters.iterator();
    }
    if (this.iterator.hasNext()) {
      FilterTemplate nextFilter = (FilterTemplate) this.iterator.next();
      nextFilter.doFilter(request, response, this);
    }
  }
}
